import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import '../model/cartInfo.dart';

class CartProvider with ChangeNotifier {
  String cartString = "[]";
  List<CartInfoMode> cartList = [];
  double allPrice = 0;
  int allGoodsCount = 0;
  bool isAllCheck = true;

  // 增加购物车商品
  void save(goodsId, goodsName, count, price, images) async {
    // 初始化
    SharedPreferences prefs = await SharedPreferences.getInstance();

    // 获取持久化值
    cartString = prefs.get('cartString');

    var temp = cartString == null ? [] : json.decode(cartString.toString());

    // 把获取的值转化为list
    List<Map> tempList = (temp as List).cast();

    // 声明标志位表示是否已经存在商品
    bool isHave = false;
    int ival = 0; //标记索引值
    tempList.forEach((item) {
      if(item['goodsId']==goodsId) {
        tempList[ival]['count']++;
        isHave=true;
      }
      ival++;
    });
    if(!isHave) {
      Map<String, dynamic> newGoods = {
        'goodsId': goodsId,
        'goodsName': goodsName,
        'count': count,
        'price': price,
        'images': images,
        'isCheck': true
      };
      tempList.add(newGoods);
      cartList.add(CartInfoMode.fromJson(newGoods));
      allGoodsCount += count;
      allPrice += count * price;
    }
    cartString = json.encode(tempList).toString();
    print(cartString);
    print(cartList);
    prefs.setString('cartString', cartString);
    await getCartInfo();
  }

  // 清空购物车
  remove() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.remove('cartString');
    cartList = [];
    print('清除完成=============');
    notifyListeners();
  }

  // 得到购物车商品
  getCartInfo() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    cartString = prefs.get('cartString');
    print('++++++getCartInfo++++++$isAllCheck');
    cartList = [];
    allGoodsCount = 0;
    allPrice = 0;
    isAllCheck = true;
    if(cartString != null) {
      List<Map> tempList = (json.decode(cartString.toString()) as List).cast();
      tempList.forEach((item) {
        cartList.add(CartInfoMode.fromJson(item));
        if(item['isCheck']) {
          allGoodsCount += item['count'];
          allPrice += item['count'] * item['price'];
        } else {
          isAllCheck = false;
        }
      });
    }
    notifyListeners();
  }

  // 删除单个商品
  deleteOneGoods(String goodsId) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    cartString = prefs.get('cartString');
    List<Map> tempList = (json.decode(cartString.toString()) as List).cast();

    int tempIndex = 0;
    int delIndex = 0;
    tempList.forEach((item) {
      if(item['goodsId'] == goodsId) {
        delIndex = tempIndex;
      }
      tempIndex++;
    });
    tempList.removeAt(delIndex);
    cartString = json.encode(tempList).toString();
    prefs.setString('cartString', cartString);
    await getCartInfo();
  }

  // 商品单选按钮状态
  changeCheckState(CartInfoMode cartItem) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    cartString = prefs.get('cartString');
    List<Map> tempList = (json.decode(cartString.toString()) as List).cast();

    int tempIndex=0, changeIndex = 0;
    tempList.forEach((item) {
      if(item['goodsId'] == cartItem.goodsId) {
        changeIndex = tempIndex;
      }
      tempIndex++;
    });
    tempList[changeIndex] = cartItem.toJson();
    cartString = json.encode(tempList).toString();
    prefs.setString('cartString', cartString);
    await getCartInfo();
  }

  // 全选状态修改
  changeAllCheckState(bool val) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    cartString = prefs.get('cartString');
    List<Map> tempList = (json.decode(cartString.toString()) as List).cast();
    List<Map> newList = [];
    for (var i = 0; i < tempList.length; i++) {
      var item = tempList[i];
      item['isCheck'] = val;
      newList.add(item);
    }
    cartString = json.encode(newList).toString();
    prefs.setString('cartString', cartString);
    await getCartInfo();
  }

  // 商品数量加减
  addOrReduceAction(CartInfoMode cartItem, bool isAdd) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    cartString = prefs.get('cartString');
    List<Map> tempList = (json.decode(cartString.toString()) as List).cast();
    int changeIndex = 0;
    for (var i = 0; i < tempList.length; i++) {
      if(tempList[i]['goodsId'] == cartItem.goodsId) {
        changeIndex = i;
        break;
      }
    }
    if (isAdd) {
      cartItem.count++;
    } else if (cartItem.count > 1) {
      cartItem.count--;
    }
    tempList[changeIndex] = cartItem.toJson();
    cartString = json.encode(tempList).toString();
    prefs.setString('cartString', cartString);
    await getCartInfo(); 
  }
}